<template>
  <el-card>
    <el-button
      type="primary"
      :icon="Plus"
      @click="showTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
      >添加</el-button
    >
    <el-table
      :data="trademarkList"
      border
      row-key="id"
      v-loading="loading"
      class="trademark-table"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="name" label="品牌LOGO">
        <template v-slot="scope">
          <!-- {{ scope.row }} -->
          <el-image
            :src="scope.row.logoUrl"
            style="width: 100px; height: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <!-- {{ row }} -->
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            @click="showTrademarkDialog(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="deleteItem(row)"
          ></el-button
        ></template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      :title="`${inputVal.id ? '修改' : '添加'}品牌`"
    >
      <el-form
        label-width="120px"
        ref="trademarkFormRef"
        :model="inputVal"
        :rules="trademarkFormRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="inputVal.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 
            action 上传的服务器地址
              action="/admin/product/fileUpload" 找不到服务器地址
              action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload" 会有跨域
              action="/app-dev/admin/product/fileUpload" 
                走代理服务器，解决跨域
                将来上线，请求前缀是/app-prod有问题
              :action="`${BASE_URL}/admin/product/fileUpload`"
            
            :show-file-list="false" 不显示文件列表（不能上传多张图片）
            :on-success="handleAvatarSuccess" 上传成功触发函数
              得到上传的图片地址
            :before-upload="beforeAvatarUpload" 上传之前触发函数
              限制上传图片大小和类型  
        
           -->
          <el-upload
            class="avatar-uploader"
            :action="`${Base_Url}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="inputVal.logoUrl"
              :src="inputVal.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/jpeg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTrademark">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
      class="trademark-pagination"
    />
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CTrademark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqTrademarkList,
  deleteTrademarkApi,
  addTrademarkItemApi,
  updataTrademarkApi,
} from "@/api/product/trademark";
import type {
  ItrademarkModelList,
  RecordsModel,
} from "@/api/product/model/trademarkModel";

import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormInstance } from "element-plus";

const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(100);
const background = ref(false);

const loading = ref(false);
let dialogVisible = ref(false);

/*********************** 获取品牌分页数据 *************************/
const getTrademarkList = async () => {
  loading.value = true;
  const result = await reqTrademarkList(currentPage.value, pageSize.value);
  trademarkList.value = result.records;
  total.value = result.total;
  loading.value = false;
};

onMounted(getTrademarkList);

let trademarkList = ref<ItrademarkModelList>([]);

/*********************** 添加品牌 *************************/
// 对话框显示或隐藏

const trademarkFormRef = ref<FormInstance>();

const inputVal = reactive({
  tmName: "",
  logoUrl: "",
  id: 0,
});

const trademarkFormRules = reactive({
  tmName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  logoUrl: [{ required: true, message: "请输入品牌LOGO" }],
});

const addTrademark = async () => {
  // trademarkFormRef.value?.validate((valid, fields) => {
  // console.log(valid, fields);

  // if (valid) {
  //   console.log("校验通过");
  // } else {
  //   console.log("检验失败", fields);
  //   alert("检验失败");
  // }
  // });
  if (inputVal.id) {
    try {
      await trademarkFormRef.value?.validate();
      await updataTrademarkApi(inputVal);
      getTrademarkList();
      dialogVisible.value = false;
      inputVal.tmName = "";
      inputVal.logoUrl = "";
    } catch (err) {
      alert("修改失败");
    }
  } else {
    try {
      await trademarkFormRef.value?.validate();
      await addTrademarkItemApi(inputVal);
      getTrademarkList();
      dialogVisible.value = false;
    } catch (error) {
      alert("检验失败");
    }
  }
};

//显示添加
// const showAddtrademarkDialog = () => {
//   inputVal.tmName = "";
//   inputVal.logoUrl = "";
//   trademarkFormRef.value?.clearValidate();
//   dialogVisible.value = true;
// };

/*********************** 修改品牌 *************************/
// const updataTrademark = (row: RecordsModel) => {
//   trademarkFormRef.value?.clearValidate();
//   dialogVisible.value = true;
//   inputVal.tmName = row.tmName;
//   inputVal.logoUrl = row.logoUrl;
//   inputVal.id = row.id as number;
// };

// 封装显示添加或修改
const showTrademarkDialog = (row: RecordsModel) => {
  trademarkFormRef.value?.clearValidate();
  dialogVisible.value = true;
  inputVal.tmName = row.tmName;
  inputVal.logoUrl = row.logoUrl;
  inputVal.id = row.id as number;
};

/*********************** 上传图片 *************************/

const Base_Url = import.meta.env.VITE_API_URL;

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response
  // uploadFile
) => {
  inputVal.logoUrl = response.data;
  // console.log(response, uploadFile);
  trademarkFormRef.value?.clearValidate(["logoUrl"]);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile.type  上传图片类型
  // rawFile.size  上传图片大小
  const rawFileType = ["image/jpeg", "image/jpg", "image/png"];
  if (!rawFileType.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须为jpeg、jpg或者png");
    return false; //返回false取消上传
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小不能超过200Kb");
    return false;
  }
  return true; //返回true确认上传
};

/*********************** 删除单个品牌数据 *************************/
const deleteItem = (row: RecordsModel) => {
  ElMessageBox.confirm(`确定删除 ${row.tmName} 吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteTrademarkApi(row.id as number);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
</script>

<style scoped lang="scss">
.trademark-table {
  margin: 30px 0;
}
// scoped模式下 只能修改自身的样式 如果要修改子组件的样式 需要使用深度选择器
/* .trademark-pagination :deep(.el-pagination__total) {
  position: absolute;
  right: 30px;
}
.trademark-pagination :deep(.el-pagination__sizes) {
  position: absolute;
  right: 100px;
} */
.trademark-pagination :deep() {
  .el-pagination__total {
    position: absolute;
    right: 30px;
  }
  .el-pagination__sizes {
    position: absolute;
    right: 100px;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
